import { Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalTypes } from 'src/app/store/reducers/member.reducer';
import { codeJson } from 'src/app/utils/base64';

export type loginParams = {
  phone: string;
  password: string;
  remember: boolean;
}

@Component({
  selector: 'app-wy-layer-login',
  templateUrl: './wy-layer-login.component.html',
  styleUrls: ['./wy-layer-login.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class WyLayerLoginComponent implements OnInit,OnChanges {
  @Input() wyRememberLogin!: loginParams;
  @Output() onChangeModalType = new EventEmitter<ModalTypes>();
  @Output() onLogin = new EventEmitter<loginParams>();
  ModalTypes = ModalTypes;
  formModel!: FormGroup;
  constructor(
    private fb: FormBuilder
  ) {
  }
  ngOnChanges(changes: SimpleChanges): void {
    const userLoginParams = changes['wyRememberLogin']
    if(userLoginParams){
      let phone = '';
      let password = '';
      let remember = false;
      const value = codeJson(userLoginParams.currentValue,'decode')
      if(value){
        phone = value.phone;
        password = value.password;
        remember = value.remember;
      }
      this.setModel({ phone, password, remember })
    }
  }

  private setModel({phone, password, remember}: loginParams){
    this.formModel = this.fb.group({
      phone: [ phone, [Validators.required, Validators.pattern(/^1\d{10}$/)] ],
      password: [ password , [Validators.required, Validators.minLength(6)] ],
      remember: [ remember ],
    })
  }

  ngOnInit(): void {
  }

  onSubmit(){
    const model = this.formModel;

    if(model.valid){
      this.onLogin.emit(model.value)
    }

  }
}
